package com.iot08.admin.controller;

import com.iot08.admin.controller.base.BaseController;
import com.iot08.admin.service.ChannelAreaService;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.admin.tools.DESEncryptTools;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.admin.ChannelArea;
import com.iot08.common.entity.admin.SysRole;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.response.Response;
import com.iot08.common.response.ResponseEnum;
import com.iot08.admin.service.ChannelAffiliationService;
import com.iot08.admin.service.RoleService;
import com.iot08.admin.service.UserService;
import com.iot08.admin.service.page.PageVO;
import com.iot08.common.utils.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Description: 用户相关控制器
 * @author: Rock
 * @time: 2020/8/12 17:29
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private ChannelAreaService channelAreaService;
    @Resource
    private ChannelAffiliationService channelAffiliationService;

    /**
     * @Description: 获取当前登录用户
     * @time: 2020/8/20 15:37
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "getLoginUser", method = RequestMethod.GET)
    public Response<Object> getLoginUser() {
        SysUser user = getSessionUser();
        if (user == null) {
            return Response.failedResponse(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        //隐藏/加密密码
        String tmpPwd = user.getPassword();
        user.setPassword((tmpPwd + "****").toUpperCase());
        return Response.successResponse(user);
    }

    /**
     * @param page
     * @param type
     * @param status
     * @param roleId
     * @time: 2020/12/17 10:27
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("list")
    public ModelAndView list(PageVO page, Integer type, Integer status, String roleId) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        if (user.getType() == Const.CHANNELUSER_TYPE) {
            mv.addObject("msg", "无权限操作");
            mv.setViewName("save_result");
            return mv;
        }
        Page<SysUser> pages = userService.list(page, type, status, roleId);
        mv.addObject("users", pages.getContent());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("status", status);
        mv.addObject("type", type);
        mv.addObject("roleId", roleId);
        mv.addObject("roles", roleService.listAll(0, 1));
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.setViewName("user/user_list");
        return mv;
    }

    /**
     * 账号管理列表
     *
     * @param page
     * @param type
     * @param status
     * @param roleId
     * @param pageType null=账号管理页面；not null=账户管理页面
     * @time: 2020/12/9 9:31
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("listFix")
    public ModelAndView listFix(PageVO page, Integer status, String roleId) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        List<SysRole> roles = new ArrayList<>();
        List<String> channelAreaIdList = new ArrayList<>();
        int areaLevel = 0;
        if (user.getType() == Const.CHANNELUSER_TYPE) {
            areaLevel = user.getChannelArea() == null ? 1 : user.getChannelArea().getLevel();
            //获取当前账号区域级别
            if (user.getChannelArea() != null) {
                channelAreaIdList = channelAreaService.listIdById(user.getChannelAreaId(), false);
            } else {
                channelAreaIdList = channelAreaService.listIdByLevel(2, user);
            }
            roles = roleService.listByLevel(areaLevel, user);
        } else {
            roles = roleService.listAll(2, 3, 4, 5);
        }
        Page<SysUser> pages = userService.listFix(page, status, roleId, channelAreaIdList, user.getType(), areaLevel);
        mv.addObject("users", pages.getContent());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("status", status);
        mv.addObject("roleId", roleId);
        mv.addObject("roles", roles);
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.addObject("user", user);
        mv.setViewName("user/user_list_fix");
        return mv;
    }

    /**
     * @Description: 添加账号页面
     * @time: 2020/8/20 17:05
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toAdd")
    public ModelAndView toAdd() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("roles", roleService.listAll(0));
        mv.addObject("channelAffs", channelAffiliationService.listAll());
        mv.setViewName("user/user_add");
        return mv;
    }

    /**
     * @time: 2020/12/9 11:21
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toAddFix")
    public ModelAndView toAddFix() {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        if (user.getType() == Const.SYSUSER_TYPE) {
            mv.addObject("msg", "系统账号不能添加账户");
            mv.setViewName("save_result");
            return mv;
        }
        //获取当前账号区域级别
        int areaLevel = user.getChannelArea() == null ? 1 : user.getChannelArea().getLevel();
        if (areaLevel == 5) {
            mv.addObject("msg", "无权限操作");
            mv.setViewName("save_result");
            return mv;
        }
        List<ChannelArea> areas = channelAreaService.listByLevel(areaLevel, user, true);
        List<SysRole> roles = roleService.listByLevel(areaLevel, user);
        mv.addObject("roles", roles);
        mv.addObject("channelAreas", areas);
        mv.addObject("channelAffiliationId", user.getChannelAffiliationId());
        mv.addObject("unbindNum", user.getUnbindNum());
        mv.setViewName("user/user_add_fix");
        return mv;
    }

    /**
     * @param [user]
     * @Description: 保存添加账号
     * @time: 2020/8/21 10:29
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ModelAndView add(SysUser user, MultipartHttpServletRequest request) throws IOException {
        ModelAndView mv = new ModelAndView();
        String msg = userService.checkAccount(user.getId(), user.getAccount());
        if (StringUtil.isBlank(msg)) {
            SysUser u = this.getSessionUser();
            user.setCreator(u.getId());
            userService.save(user, request.getFile("file"), this.getSessionUser(), this.getRemortIP());
            msg = "success";
        }
        mv.addObject("msg", msg);
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * @param [id]
     * @Description: 编辑页面
     * @time: 2020/8/21 10:28
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toEdit")
    public ModelAndView toEdit(String id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("roles", roleService.listAll(0));
        mv.addObject("channelAffs", channelAffiliationService.listAll());
        SysUser user = userService.findById(id);
        user.setPassword(DESEncryptTools.decode(user.getPassword()));
        mv.addObject("user", user);
        mv.setViewName("user/user_edit");
        return mv;
    }

    /**
     * @param id
     * @time: 2020/12/9 12:08
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toEditFix")
    public ModelAndView toEditFix(String id) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        if (user.getType() == Const.SYSUSER_TYPE) {
            mv.addObject("msg", "系统账号不能添加账户");
            mv.setViewName("save_result");
            return mv;
        }
        //获取当前账号区域级别
        int areaLevel = user.getChannelArea() == null ? 1 : user.getChannelArea().getLevel();
        if (areaLevel == 5) {
            mv.addObject("msg", "无权限操作");
            mv.setViewName("save_result");
            return mv;
        }
        List<SysRole> roles = roleService.listByLevel(areaLevel, user);
        List<ChannelArea> areas = channelAreaService.listByLevel(areaLevel, user, true);
        mv.addObject("roles", roles);
        mv.addObject("channelAreas", areas);
        mv.addObject("unbindNum", user.getUnbindNum());
        mv.addObject("user", userService.findById(id));
        mv.setViewName("user/user_edit_fix");
        return mv;
    }

    /**
     * @time: 2020/10/21 14:32
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toMyselfEdit")
    public ModelAndView toMyselfEdit() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", userService.findById(this.getSessionUser().getId()));
        mv.setViewName("user/user_myself_edit");
        return mv;
    }

    /**
     * @time: 2020/10/21 14:32
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toMyselfPwdEdit")
    public ModelAndView toMyselfPwdEdit() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", userService.findById(this.getSessionUser().getId()));
        mv.setViewName("user/user_myselfpwd_edit");
        return mv;
    }

    /**
     * @param [user]
     * @Description: 保存编辑
     * @time: 2020/8/21 10:28
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public ModelAndView edit(SysUser user, MultipartHttpServletRequest request) throws IOException {
        ModelAndView mv = new ModelAndView();
        String msg = userService.checkAccount(user.getId(), user.getAccount());
        if (StringUtil.isBlank(msg)) {
            userService.update(user, request.getFile("file"), this.getSessionUser(), this.getRemortIP());
            msg = "success";
            if (user.getId().equals(this.getSessionUser().getId())) {
                this.delSessionUser();
                mv.setViewName("redirect:login");
            } else {
                this.delSessionUserById(user.getId());
                mv.setViewName("save_result");
            }
        }
        mv.addObject("msg", msg);
        return mv;
    }

    /**
     * @param [id]
     * @Description: 删除
     * @time: 2020/8/21 10:28
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("del")
    public Response<Object> del(String id) {
        userService.updateDel(id, this.getSessionUser(), this.getRemortIP());
        this.delSessionUserById(id);
        return Response.successResponse();
    }

    /**
     * @param [id, status]
     * @Description: 更新状态
     * @time: 2020/8/21 10:28
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "updateStatus", method = RequestMethod.POST)
    public Response<Object> updateStatus(String id, Integer status) {
        userService.updateStatus(id, status, this.getSessionUser(), this.getRemortIP());
        if (status == 1) {
            this.delSessionUserById(id);
        }
        return Response.successResponse();
    }

    /**
     * @param [id, account]
     * @time: 2020/9/3 16:03
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("checkAccount")
    public Response<Object> checkAccount(String id, String account) {
        String msg = userService.checkAccount(id, account);
        if (StringUtil.isNotBlank(msg)) {
            return Response.failedResponse(msg);
        }
        return Response.successResponse();
    }

    /**
     * @param pwd
     * @time: 2020/10/21 14:57
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("checkMyselfAccountPwd")
    public Response<Object> checkAccountPwd(String pwd) {
        SysUser user = this.getSessionUser();
        String tmpPwd = (DESEncryptTools.encode(pwd)+"****").toUpperCase();
        //DigestUtils.md5Hex(pwd + "****").toUpperCase();
        if (!user.getPassword().equals(tmpPwd)) {
            return Response.failedResponse();
        }
        return Response.successResponse();
    }
}
